<?php

Yii::import( "application.controllers.FrontendBaseController" );

class CommentController extends FrontendBaseController
{
	public function actionCreate()
	{
            if (!Yii::app()->request->isAjaxRequest)
            {
                throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
            }

            $model=new Comment;

            if(!isset($_POST['Comment']))
            {
                throw new CHttpException(400, 'Invalid request. POST does not have comment data.');
            }
            $model->attributes=$_POST['Comment'];
            $model = CommentFacade::saveModel($model);
            $model->refresh();
            $this->renderPartial('ajaxCreate', array('model' => $model));
            Yii::app()->end();
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Comment']))
		{
			$model->attributes=$_POST['Comment'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->comment_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
            $comment = $this->loadModel($id);
            if (CommentFacade::isAuthor($comment))
            {
                $comment->delete();
                $this->redirect(Yii::app()->request->urlReferrer);
            }
            else
            {
                throw new CHttpException(403, 'Invalid request.');
            }
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
            return CommentFacade::loadModel($id);
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
